package com.ehouse.adapters;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.ResourceCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.ehouse.MainActivity;
import com.ehouse.R;
import com.ehouse.connection.ConnectionService;
import com.ehouse.connection.ConnectionService.IConnectionResponseListener;
import com.ehouse.database.LightTable;

public class LightItemAdapter extends ResourceCursorAdapter{
	private int layout;
	
	public LightItemAdapter (Context context, int layout, Cursor c, int flags){
		super(context, layout, c, flags);
		this.layout = layout;
	}

	    @Override
	    public View newView(Context context, Cursor cur, ViewGroup parent) {
	        LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        return li.inflate(layout, parent, false);
	    }

	    @Override
	    public void bindView(View view, final Context context, Cursor cursor) {
	    	String label = cursor.getString(cursor.getColumnIndex(LightTable.COLUMN_LABEL));
	    	boolean state = (cursor.getInt(cursor.getColumnIndex(LightTable.COLUMN_STATE)) == 1);
	    	
	    	TextView labelView = (TextView)view.findViewById(R.id.rowLabel);
            ToggleButton switchButtonView = (ToggleButton)view.findViewById(R.id.rowButton);
            
            labelView.setText(label);
            switchButtonView.setChecked(state);
            switchButtonView.setTag(label);
    		switchButtonView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
				String label = (String)buttonView.getTag();
			
				
				MainActivity.serviceRef.switchSensor("Lights", label, isChecked, new ConnectionService.IConnectionResponseListener() {
					
					public void responseReceived(Object data, boolean success) {
						if(success){
							MainActivity.serviceRef.getLights(new IConnectionResponseListener() {
								
								public void responseReceived(Object data, boolean success) {
									
									if(!success){
										Toast.makeText(context,
												R.string.connection_error, Toast.LENGTH_LONG)
												.show();
		
									}
										
								}
							});
						}else{
							Toast.makeText(context,
									R.string.connection_error, Toast.LENGTH_LONG)
									.show();

						}
					}
				});
			}
		});
	    }


}
